package com.vvv.btcpricealert.job;

import com.vvv.btcpricealert.dto.CoinCapResponse;
import com.vvv.btcpricealert.dto.PriceAlert;
import com.vvv.btcpricealert.mapper.PriceAlertMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author vvv
 * @date 2025/3/5 14 42
 * discription
 */
@Component
public class BTCPriceAlertJob {

    @Value("${btc.api}")
    private String API_URL;
    @Value("${btc.threshold.percent}")
    private double THRESHOLD_PERCENT;
    private final RestTemplate restTemplate = new RestTemplate();
    private final Queue<Double> priceHistory = new LinkedList<>();

    @Resource
    private PriceAlertMapper priceAlertMapper;

    @Scheduled(fixedRate = 60000) // 每分钟执行一次
    public void checkBtcPrice() {
        try {
            double currentPrice = fetchCurrentPrice();
            if (currentPrice <= 0) return;

            System.out.println(LocalDateTime.now() + "BTC当前的价格为：" + currentPrice);
            if (priceHistory.size() >= 5) {
                double oldPrice = priceHistory.poll(); // 取出 5 分钟前的价格
                double changePercent = ((currentPrice - oldPrice) / oldPrice) * 100;

                if (Math.abs(changePercent) >= THRESHOLD_PERCENT) {
                    String status = changePercent > 0 ? "上涨" : "下跌";
                    System.out.printf("[ALERT] %s BTC 价格 %.2f USD (%.2f%%) 时间: %s\n",
                            status, currentPrice, changePercent, LocalDateTime.now());
                    PriceAlert priceAlert = PriceAlert.builder()
                            .alertTime(LocalDateTime.now())
                            .price(currentPrice)
                            .status(status)
                            .changePercent(changePercent)
                            .build();
                    priceAlertMapper.insert(priceAlert);
                }
            }

            priceHistory.add(currentPrice); // 记录当前价格
        } catch (Exception e) {
            System.err.println("获取 BTC 价格失败: " + e.getMessage());
        }
    }

    public double fetchCurrentPrice() {
        try {
            var response = restTemplate.getForObject(API_URL, CoinCapResponse.class);
            if (response != null && response.getData() != null) {
                return Double.parseDouble(response.getData().getPriceUsd());
            }
        } catch (Exception e) {
            System.err.println("API 请求失败: " + e.getMessage());
        }
        return -1;
    }
}
